﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RazorWebApp.Utils.ViewComponentExtension
{
    [ViewComponent(Name ="StudentList")] //1、自定义组件名，如果没有设置，则会取StudentViewComponent中的"Student"为组件名
    public class StudentViewComponent: ViewComponent  //2、继承ViewComponent类
    {
        /// <summary>
        /// 3、定义异步的InvokeAsync方法，它是返回组件内容的方法，这里的方法类似控制器中的方法
        /// </summary>
        /// <returns></returns>
        public async Task<IViewComponentResult> InvokeAsync()
        {
            ViewBag.UserName = "007";//用户名
            var list = await GetStudents();
            return View(list);
            //return View("~/Views/Shared/Components/StudentList/Default.cshtml",list);  //可自定义返回的cshtml路径
        }

        /// <summary>
        /// 4、获取学生数据
        /// </summary>
        /// <returns></returns>
        public Task<List<Student>> GetStudents()
        {
            return Task.Run(() =>
            {
                return new List<Student>()
                {
                    new Student(){ Id=1,Name="小明"},
                    new Student(){ Id=2,Name="小红"},
                    new Student(){ Id=3,Name="小兰"},
                    new Student(){ Id=4,Name="小李"},
                    new Student(){ Id=5,Name="小王"},
                    new Student(){ Id=6,Name="小刚"},
                };
            });
        }
    }

    /// <summary>
    /// 学生类
    /// </summary>
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
